package com.lvy.hczn.front.system.service.impl;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import javax.validation.Validator;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lvy.hczn.front.common.constant.Constants;
import com.lvy.hczn.front.common.constant.MqConstants;
import com.lvy.hczn.front.common.core.domain.entity.SysDictData;
import com.lvy.hczn.front.common.exception.UtilException;
import com.lvy.hczn.front.common.utils.DictUtils;
import com.lvy.hczn.front.system.domain.business.AccessManager;
import com.lvy.hczn.front.system.domain.business.Warehouse;
import com.lvy.hczn.front.system.domain.business.dto.Sorter;
import com.lvy.hczn.front.system.service.WarehouseService;
import com.lvy.hczn.mq.rocket.ParamInfo;
import com.lvy.hczn.mq.rocket.ProducerUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.lvy.hczn.front.common.annotation.DataScope;
import com.lvy.hczn.front.common.constant.UserConstants;
import com.lvy.hczn.front.common.core.domain.entity.SysRole;
import com.lvy.hczn.front.common.core.domain.entity.SysUser;
import com.lvy.hczn.front.common.core.text.Convert;
import com.lvy.hczn.front.common.exception.ServiceException;
import com.lvy.hczn.front.common.utils.ShiroUtils;
import com.lvy.hczn.front.common.utils.StringUtils;
import com.lvy.hczn.front.common.utils.bean.BeanValidators;
import com.lvy.hczn.front.common.utils.security.Md5Utils;
import com.lvy.hczn.front.common.utils.spring.SpringUtils;
import com.lvy.hczn.front.system.domain.system.SysPost;
import com.lvy.hczn.front.system.domain.system.SysUserPost;
import com.lvy.hczn.front.system.domain.system.SysUserRole;
import com.lvy.hczn.front.system.mapper.SysPostMapper;
import com.lvy.hczn.front.system.mapper.SysRoleMapper;
import com.lvy.hczn.front.system.mapper.SysUserMapper;
import com.lvy.hczn.front.system.mapper.SysUserPostMapper;
import com.lvy.hczn.front.system.mapper.SysUserRoleMapper;
import com.lvy.hczn.front.system.service.ISysConfigService;
import com.lvy.hczn.front.system.service.ISysUserService;

/**
 * 用户 业务层处理
 *
 * @author ruoyi
 */
@Service
@Slf4j
public class SysUserServiceImpl implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    protected Validator validator;

    @Autowired
    private ProducerUtil producerUtil;

    @Autowired
    private WarehouseService warehouseService;

    /**
     * 根据条件分页查询用户列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUserList(SysUser user) {
        return userMapper.selectUserList(user);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectAllocatedList(SysUser user) {
        return userMapper.selectAllocatedList(user);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     *
     * @param user 用户信息
     * @return 用户信息集合信息
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<SysUser> selectUnallocatedList(SysUser user) {
        return userMapper.selectUnallocatedList(user);
    }

    /**
     * 通过用户名查询用户
     *
     * @param userName 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByLoginName(String userName) {
        return userMapper.selectUserByLoginName(userName);
    }

    /**
     * 通过手机号码查询用户
     *
     * @param phoneNumber 手机号码
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByPhoneNumber(String phoneNumber) {
        return userMapper.selectUserByPhoneNumber(phoneNumber);
    }

    /**
     * 通过邮箱查询用户
     *
     * @param email 邮箱
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByEmail(String email) {
        return userMapper.selectUserByEmail(email);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    /**
     * 通过用户ID查询用户和角色关联
     *
     * @param userId 用户ID
     * @return 用户和角色关联列表
     */
    @Override
    public List<SysUserRole> selectUserRoleByUserId(Long userId) {
        return userRoleMapper.selectUserRoleByUserId(userId);
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(String ids) {
        Long[] userIds = Convert.toLongArray(ids);
        for (Long userId : userIds) {
            checkUserAllowed(new SysUser(userId));
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 新增保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SysUser user) {
        // 新增用户信息
        int rows = userMapper.insertUser(user);
        // 新增用户岗位关联
        insertUserPost(user);
        // 新增用户与角色管理
        insertUserRole(user.getUserId(), user.getRoleIds());
        return rows;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        user.setUserType(UserConstants.REGISTER_USER_TYPE);
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SysUser user) {
        Long userId = user.getUserId();
        if (user.getRoleIds() != null && user.getRoleIds().length > 0) {
            // 删除用户与角色关联
            userRoleMapper.deleteUserRoleByUserId(userId);
            // 新增用户与角色管理
            insertUserRole(user.getUserId(), user.getRoleIds());
        }
        if (user.getPostIds() != null && user.getPostIds().length > 0) {
            // 删除用户与岗位关联
            userPostMapper.deleteUserPostByUserId(userId);
            // 新增用户与岗位管理
            insertUserPost(user);
        }

        return userMapper.updateUser(user);
    }

    /**
     * 修改用户个人详细信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserInfo(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户密码
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int resetUserPwd(SysUser user) {
        return updateUserInfo(user);
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotNull(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>();
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                userRoleMapper.batchUserRole(list);
            }
        }
    }

    /**
     * 新增用户岗位信息
     *
     * @param user 用户对象
     */
    public void insertUserPost(SysUser user) {
        Long[] posts = user.getPostIds();
        if (StringUtils.isNotNull(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>();
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(user.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            if (list.size() > 0) {
                userPostMapper.batchUserPost(list);
            }
        }
    }

    /**
     * 校验用户名称是否唯一
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean checkLoginNameUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkLoginNameUnique(user.getLoginName());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public boolean checkEmailUnique(SysUser user) {
        Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
        SysUser info = userMapper.checkEmailUnique(user.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public SysUser selectByEmail(String email) {
        if (StrUtil.isEmpty(email)) {
            throw new UtilException("参数为空");
        }
        return userMapper.checkEmailUnique(email);
    }

    /**
     * 校验用户是否允许操作
     *
     * @param user 用户信息
     */
    @Override
    public void checkUserAllowed(SysUser user) {
        if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(ShiroUtils.getUserId())) {
            SysUser user = new SysUser();
            user.setUserId(userId);
            List<SysUser> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users)) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 查询用户所属角色组
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(Long userId) {
        List<SysRole> list = roleMapper.selectRolesByUserId(userId);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(Long userId) {
        List<SysPost> list = postMapper.selectPostsByUserId(userId);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByLoginName(user.getLoginName());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(Md5Utils.hash(user.getLoginName() + password));
                    user.setCreateBy(operName);
                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    checkUserAllowed(u);
                    checkUserDataScope(u.getUserId());
                    user.setUserId(u.getUserId());
                    user.setUpdateBy(operName);
                    userMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getLoginName() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getLoginName() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getLoginName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 用户状态修改
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int changeStatus(SysUser user) {
        return userMapper.updateUser(user);
    }

    /**
     * 同步分拣员账户更新到本地
     *
     * @param list
     * @return void
     * @author yw
     * @date 2023-06-10 16:28:09
     */
    @Override
    public synchronized void syncSorterFromTransmit(List<ParamInfo<Sorter>> list) {
        if (list == null || list.isEmpty()) {
            throw new UtilException("参数为空");
        }
        log.error("syncSorterFromTransmit:{}", JSONUtil.toJsonStr(list));
        for (ParamInfo<Sorter> info : list) {
            List<Sorter> sorterList = info.getList();
            if (StringUtils.isEmpty(info.getWarehouseCode())) {
                throw new UtilException("仓库编号为空");
            }
            if (sorterList == null || sorterList.isEmpty()) {
                throw new UtilException("参数信息为空，请检查数据格式");
            }
            Warehouse warehouse = warehouseService.getOne(Wrappers.<Warehouse>lambdaQuery().eq(Warehouse::getWarehouseCode, info.getWarehouseCode()).eq(Warehouse::getStatus, Constants.WAREHOUSE_STATUS_ENABLE).orderByDesc(Warehouse::getCreateTime).last("limit 1"));
            if (warehouse == null) {
                throw new UtilException(info.getWarehouseCode() + "仓库信息为空");
            }
            String topic = warehouseService.selectRegionAreaTopic(warehouse);
            List<SysUser> userList = new ArrayList<>();
            for (Sorter sorter : sorterList) {
                if (StringUtils.isEmpty(sorter.getSorterId())) {
                    throw new UtilException("ID为空");
                }

                if (StringUtils.isEmpty(sorter.getStatus())) {
                    throw new UtilException("账号状态为空");
                }

                SysUser user = new SysUser();
                BeanUtil.copyProperties(sorter, user, false);
                if (StringUtils.isEmpty(user.getLoginName())) {
                    throw new UtilException(user.getLoginName() + "登录账户为空");
                }
                if (!cn.hutool.core.lang.Validator.isMobile(user.getLoginName())) {
                    throw new UtilException("登录账户必须为手机号");
                }
                //系统未指定来源，则使用默认
                if (StringUtils.isEmpty(sorter.getSourceId())) {
                    user.setEmail(Constants.SOURCE_ID_DEFAULT + sorter.getSorterId() + "@qq.com");
                } else {
                    user.setEmail(sorter.getSourceId() + sorter.getSorterId() + "@qq.com");
                }

                SysUser sysUser = userMapper.checkLoginNameUnique(user.getLoginName());
                if (sorter.getStatus().equals(Constants.WAREHOUSE_STATUS_RESET)) {
                    /**修改密码**/
                    if (sysUser == null) {
                        throw new UtilException(user.getLoginName() + "账户信息不存在");
                    }
                    user.setPassword(sorter.getPasswordInfo());
                    if (StringUtils.isEmpty(user.getPassword())) {
                        throw new UtilException("密码为空");
                    }
                    this.checkUserAllowed(sysUser);
                    this.checkUserDataScope(sysUser.getUserId());
                    sysUser.setSalt(ShiroUtils.randomSalt());
                    sysUser.setPassword(new Md5Hash(user.getLoginName() + user.getPassword() + sysUser.getSalt()).toHex());
                    if (this.resetUserPwd(sysUser) > 0) {
                        if (ShiroUtils.getUserId().longValue() == sysUser.getUserId().longValue()) {
                            ShiroUtils.setSysUser(this.selectUserById(sysUser.getUserId()));
                        }
                        log.error("修改用户密码：{}", JSONUtil.toJsonStr(user));
                        userList.add(sysUser);
                    }
                } else {
                    /**新增或修改**/
                    Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId();
                    if (StringUtils.isNotNull(sysUser) && sysUser.getUserId().longValue() != userId.longValue()) {
                        user.setUserId(sysUser.getUserId());
                    }
                    if (StringUtils.isNotEmpty(user.getPhonenumber()) && !this.checkPhoneUnique(user)) {
                        throw new UtilException("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
                    }

                    user.setPhonenumber(user.getLoginName());
                    if (user.getUserId() == null) {
                        user.setPassword(sorter.getPasswordInfo());
                        if (StringUtils.isEmpty(user.getPassword())) {
                            throw new UtilException("密码为空");
                        }
                        user.setSalt(ShiroUtils.randomSalt());
                        user.setPassword(new Md5Hash(user.getLoginName() + "123456" + user.getSalt()).toHex());
//                    user.setCreateBy(ShiroUtils.getSysUser().getLoginName());
                        user.setUserType(UserConstants.REGISTER_USER_TYPE);
                        initPostRole(user);
                        this.insertUser(user);
                    } else {
                        if (!StringUtils.isEmpty(user.getStatus())) {
                            if (user.getStatus().equals(UserConstants.NORMAL)) {
                                user.setDelFlag("0");
                                userMapper.updateUser(user);
                            } else {
                                user.setDelFlag("2");
                                deleteUserById(user.getUserId());
                            }
                        }
                    }
                    userList.add(user);
                }

                /**门禁**/
                AccessManager accessManager = new AccessManager();
                ParamInfo<AccessManager> paramInfo = new ParamInfo<>();
                paramInfo.setWarehouseCode(warehouse.getWarehouseCode());
                accessManager.setSourceCode(sorter.getLoginName());
                if (StrUtil.isEmpty(sorter.getSortCode())) {
                    accessManager.setAccessCode(sorter.getLoginName());
                } else {
                    accessManager.setAccessCode(sorter.getSortCode());
                }
                accessManager.setType(Integer.valueOf(Constants.ACCESS_TYPE_ONE));
                paramInfo.setData(accessManager);
                String tag = warehouse.getWarehouseCode() + "_" + MqConstants.TOPIC_WAREHOUSE_LEASE;
                try {
                    producerUtil.sendMsg(topic, tag, JSON.toJSONString(paramInfo).getBytes(StandardCharsets.UTF_8), IdUtil.fastSimpleUUID());
                } catch (Exception e) {
                    throw new UtilException("数据转发异常");
                }
            }
            log.error("用户信息：{}", JSONUtil.toJsonStr(userList));
            if (!userList.isEmpty()) {
                ParamInfo<SysUser> userParamInfo = new ParamInfo<>();
                userParamInfo.setList(userList);
                String tag = warehouse.getWarehouseCode() + "_" + MqConstants.TOPIC_WAREHOUSE_SORTER_USER;
                try {
                    producerUtil.sendAsyncMsg(topic, tag, JSON.toJSONString(userParamInfo).getBytes(StandardCharsets.UTF_8), IdUtil.fastSimpleUUID());
                } catch (Exception e) {
                    throw new UtilException("信息发送异常");
                }
            }
        }
    }

    /**
     * 初始化岗位和角色
     *
     * @param user
     * @return void
     * @author yw
     * @date 2023-06-10 19:50:41
     */
    @Override
    @Transactional
    public void initPostRole(SysUser user) {
        List<SysDictData> sysDictDataList = DictUtils.getDictCache(Constants.SYS_DICT_SORTER_POST_ROLE);
        if (sysDictDataList != null) {
            for (SysDictData dictData : sysDictDataList) {
                if (dictData.getDictLabel().equals(Constants.SYS_DICT_SORTER_ROLE)) {
                    SysRole info = roleMapper.checkRoleKeyUnique(dictData.getDictValue());
                    if (info == null) {
                        throw new UtilException("无相关角色");
                    }
                    user.setRoleIds(new Long[]{info.getRoleId()});
                } else if (dictData.getDictLabel().equals(Constants.SYS_DICT_SORTER_POST)) {
                    SysPost info = postMapper.checkPostCodeUnique(dictData.getDictValue());
                    if (info == null) {
                        throw new UtilException("无相关岗位");
                    }
                    user.setPostIds(new Long[]{info.getPostId()});
                }
            }
        }
    }
}
